A better way to implement singleton desygn pattern and resquest data from a json file to connect to a database mysql. this is from my development project.
<?php
namespace Simulab\Simulab\models\connections;
class SimulabConnection
{
private static $instance = null;
private static $pdo = null;
private function __construct()
{
}
public static function getJsonData():object{
$filename = '../../config/json/sgbd_informations.json';
if (file_exists($filename)) {
$data = file_get_contents($filename);
$infodb= json_decode($data);
return $infodb;
}else{
return null;
}
}
public static function connect():?\PDO{
if (is_null(self::$instance)) {
self::$instance = new self;
$infodb= self::getJsonData()!=null?self::getJsonData():null;
$server= $infodb->server;
$database= $infodb->database;
$user= $infodb->user;
$password= $infodb->password;
$options= [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
self::$pdo = new \PDO("mysql:host=$server;dbname=$database", $user, $password, $options);
}
return self::$pdo;
}
}